import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

import '../EJ_webview/EM_WebViewPage.dart';
import '../tools/FL_CustomLoading.dart';
import '../tools/KaL_Config.dart';
import '../tools/MMPermissionHelper.dart';
import '../tools/models/KL_keralaLottoDataModel.dart';
import '../tools/models/KaL_DataViewModels.dart';
import '../tools/models/KaL_LottoModel.dart';
import 'drawer/EJ_YDContactusVC.dart';
import 'views/EJ_Generator_HomgPage.dart';
import 'views/EJ_HeaderView_HomePage.dart';
import 'views/EJ_ResultView_HomePage.dart';
import 'views/EJ_StaticEnter_HomePage.dart';

class EJHomePageVC extends StatefulWidget {
  EJHomePageVC({super.key, this.pageController});
  PageController? pageController;

  @override
  State<EJHomePageVC> createState() => _EJHomePageVCState();
}

class _EJHomePageVCState extends State<EJHomePageVC>
    with AutomaticKeepAliveClientMixin {
  //
  late ScrollController _controller = ScrollController();

  // late var hideLoading = false; //
  var notify_isGranted = false;
  final _scaffoldkey = GlobalKey<ScaffoldState>();
  late KaL_LottoModel _model;

  bool _isLoading = true;

  String _authStatus = 'Unknown';
  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlugin() async {
    final TrackingStatus status =
        await AppTrackingTransparency.trackingAuthorizationStatus;
    setState(() => _authStatus = '$status');
    // If the system can show an authorization request dialog
    if (status == TrackingStatus.notDetermined) {
      // Show a custom explainer dialog before the system dialog
      await showCustomTrackingDialog(context);
      // Wait for dialog popping animation
      await Future.delayed(const Duration(milliseconds: 200));
      // Request system's tracking authorization dialog
      final TrackingStatus status =
          await AppTrackingTransparency.requestTrackingAuthorization();
      setState(() => _authStatus = '$status');
    }

    ///获取到uuid
    final uuid = await AppTrackingTransparency.getAdvertisingIdentifier();
    debugPrint("UUID: $uuid");
  }

  Future<void> showCustomTrackingDialog(BuildContext context) async =>
      await showDialog<void>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('Dear User'),
          content: const Text(
            'We care about your privacy and data security. We keep this app free by showing ads. '
            'Can we continue to use your data to tailor ads for you?\n\nYou can change your choice anytime in the app settings. '
            'Our partners will collect data and use a unique identifier on your device to show you ads.',
          ),
          actions: [
            TextButton(
              // onPressed: () => Navigator.pop(context),
              onPressed: () {
                hidenCustomTrackingDialog(context);
              },
              child: const Text('Continue'),
            ),
          ],
        ),
      );

  void hidenCustomTrackingDialog(BuildContext context) {
    Navigator.pop(context);
    // if (_isLoading) {
    //   BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
    //     return FLCustomLoading(
    //       title: 'Loading...',
    //     );
    //   });
    // }
  }

  MM_configPermission() async {
    debugPrint('++++++获取推送权限');
    MMPermissionHelper().check(
      [
        Permission.notification,
        // Permission.appTrackingTransparency
      ],
      onSuccess: () {
        debugPrint('notification-onSuccess');
        setState(() {});
      },
      onFailed: () {
        debugPrint('notification-onFailed');
        setState(() {});
      },
      onOpenSetting: () {
        debugPrint('-notification-onOpenSetting');
      },
    );
  }

  _getAllResults() async {
    var dataCount = 100;
    bool res = await KaL_DataViewModels().getData(dataCount);
    if (res) {
      _isLoading = false;
      // _hidenLoading();
      debugPrint('request count $dataCount');
      setState(() {});
    }
  }

  _EJ_readPolicy() {
    debugPrint('NL_readPolicy');
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => const EJWebViewPage(
              url: KaL_Config.KaL_policy,
              haveAppBar: true,
              title: 'Privacy Policy')),
    );
  }

  _EJ_readTerms() {
    debugPrint('NL_readTerms');
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => const EJWebViewPage(
                url: KaL_Config.KaL_terms,
                haveAppBar: true,
                title: 'Terms & Conditions',
              )),
    );
  }

  _EJ_goContactUS() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const EJ_YDContactusVC()),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller.dispose(); // 释放控制器
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    // MM_configPermission();

    // ///请求跟踪权限
    // WidgetsFlutterBinding.ensureInitialized()
    //     .addPostFrameCallback((_) => initPlugin());

    // Future<bool> isGet = KL_keralaLottoDataModel().getNextDrawnData();

    ///接口原因：在启动页时就加载全部数据，后面可能优化在打开下面两个方法
    // _getAllResults();
    // _showLoading();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    ///
    _model = KaL_DataViewModels().AL_lottoModel;

    return Scaffold(
      backgroundColor: KaL_Config.KaL_pageBgColor,
      endDrawer: RightDrawer(
        onTap: (p0) {
          debugPrint('$p0');
          switch (p0) {
            case 0:
              _EJ_readPolicy();
            case 1:
              _EJ_readTerms();
            case 2:
              _EJ_goContactUS();

              break;
            default:
          }
        },
      ), // 设置右侧抽屉
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: KaL_Config.KaL_navgatBarColor,
        foregroundColor: KaL_Config.KaL_navgatBarTitleColor,
        title: Image.asset(
          'assets/sys_imgs/DearLottery Logo.png',
          width: 160,
          height: 50,
        ),
        actions: [
          Builder(
            //解决点击按钮没反应
            builder: (BuildContext context) {
              return IconButton(
                icon: const Icon(Icons.menu),
                onPressed: () {
                  // 打开右侧抽屉
                  Scaffold.of(context).openEndDrawer();
                },
              );
            },
          ),
        ],
      ),
      // body: Container(
      //   width: double.infinity,
      //   height: double.infinity,
      //   color: Colors.red,
      // ),
      body: ListView(
        controller: _controller,
        children: [
          EJHeaderView_HomePage(
            model: _model,
            nextDrawnModel: KL_keralaLottoDataModel().nextDrawnModel,
          ),
          EJResultView_HomePage(
            pageController: widget.pageController,
          ),
          EJStaticEnter(
            pageController: widget.pageController,
          ),
          EJGenerator_HomePage(
            pageController: widget.pageController,
          ),
          // !notify_isGranted ? EJNotifyView_HomePage() : Container(),
        ],
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class RightDrawer extends StatelessWidget {
  //回传点击事件
  final Function(int) onTap;
  RightDrawer({required this.onTap});

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Container(
        color: KaL_Config.KaL_MainColor,
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
              child: Center(
                child: Container(
                  decoration: const BoxDecoration(
                      // color: Colors.yellow,
                      borderRadius: BorderRadius.all(Radius.circular(8))),
                  child: ClipRRect(
                      borderRadius: BorderRadius.circular(8), //
                      child: Image.asset(
                        'assets/sys_imgs/DearLottery Logo.png',
                        width: 180,
                        height: 124,
                      )),
                ),
              ),
            ),
            listTile(context, 'Privacy Policy', 0),
            listTile(context, 'Terms & Conditions', 1),
            listTile(context, 'Contact us', 2),
          ],
        ),
      ),
    );
  }

  Widget listTile(
    BuildContext context,
    String title,
    int index,
  ) {
    return ListTile(
      trailing: const Icon(
        Icons.arrow_right_outlined,
        color: Colors.white, // 自定义颜色
        size: 24.0, // 自定义大小
      ),
      title: Text(
        title,
        style:
            const TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
      ),
      onTap: () {
        // 处理点击事件
        Navigator.pop(context); // 关闭抽屉
        onTap(index);
      },
    );
  }
}
